//
//  ShMyCollectListViewController.m
//  yunyan
//
//  Created by chirui on 2018/5/2.
//  Copyright © 2018年 haichuang. All rights reserved.
//

#import "ShMyCollectListViewController.h"
#import "CollectListTableViewCell.h"
#import "NewsDetailsViewController.h"
#import "ActiveDetailViewController.h"
#import "SHNesHomeTableViewCell.h"

@interface ShMyCollectListViewController ()<UITableViewDelegate,UITableViewDataSource>{
    
    UITableView * _tableView;
    NSMutableArray * _dataArray;
    int page;
}

@end

@implementation ShMyCollectListViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
   
    page = 1;
    self.view.backgroundColor = [UIColor whiteColor];
    _dataArray = @[].mutableCopy;
    [self creatTableView];
    
    if (_isShare) {
        
        [self customNaviItemTitle:@"分享记录" isLeft:YES];
        [self getShareRequest];
    }else{
        
        [self customNaviItemTitle:@"我的收藏" isLeft:YES];
         [self getCollectRequest];
    }
}

-(void)creatTableView {
    
    _tableView =[[UITableView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight-SH_TopHeight) style:UITableViewStyleGrouped];
    _tableView.dataSource = self;
    _tableView.delegate = self;
    _tableView.backgroundColor =[UIColor groupTableViewBackgroundColor];
    UIView * view =[[UIView alloc]init];
    _tableView.tableFooterView = view;
    [self.view addSubview:_tableView];
    
    [_tableView registerNib:[UINib nibWithNibName:[CollectListTableViewCell reuseIdentifier] bundle:nil] forCellReuseIdentifier:[CollectListTableViewCell reuseIdentifier]];
    
     [_tableView registerNib:[UINib nibWithNibName:@"SHNesHomeTableViewCell" bundle:nil] forCellReuseIdentifier:@"SHNesHomeTableViewCell"];
    
    MJRefreshNormalHeader * header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
       
        page = 1;
        if (_dataArray) {
             [_dataArray removeAllObjects];
        }
        
        if (_isShare) {
        
            [self getShareRequest];
        }else{
            
            [self getCollectRequest];
        }
    }];
    _tableView.mj_header = header;
    
}


-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return _dataArray.count;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    NSDictionary * dic = _dataArray[indexPath.row];
    NSArray * imageArray = dic[@"cover_pic"];
    
    if (imageArray.count!=1) {
        
        
        UILabel * titleLabel  = [[UILabel alloc]initWithFrame:CGRectMake(10, 15, WIDTH -20, 20)];
        titleLabel.text = dic[@"title"];
        titleLabel.font = [UIFont systemFontOfSize:16];
        titleLabel.numberOfLines = 2;
        [titleLabel sizeToFit];
        
        CGFloat widthImage = (WIDTH -40)/3;
        UIImageView * image;
        if (imageArray.count==0) {
            
            image = [[UIImageView alloc]initWithFrame:CGRectMake(10,CGRectGetMaxY(titleLabel.frame)+10 ,10 ,1)];
        }else {
            
            for (int i = 0; i<imageArray.count; i++) {
                
                image = [[UIImageView alloc]initWithFrame:CGRectMake(10+widthImage*i+10*i, CGRectGetMaxY(titleLabel.frame)+10, widthImage, widthImage *0.6)];
                [image sd_setImageWithURL:ImageUrl(imageArray[i])];
                image.layer.cornerRadius = 3.f;
                image.layer.masksToBounds = YES;
                
            }
            
        }
        
        return CGRectGetMaxY(image.frame)+40;
        
    }else{
        
        return 100.0f;
    }
   
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    return 10;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    
    return 0.01;
    
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    NSDictionary * dic = _dataArray[indexPath.row];
    
    
    if (_isShare) {
        
        if ([dic[@"type"] intValue]==1) {
            
            NSLog(@"新闻");
            NewsDetailsViewController * homeDetiel = [[NewsDetailsViewController alloc]init];
            homeDetiel.news_idStr = [NSString stringWithFormat:@"%ld",[dic[@"news_id"] integerValue]];
            //        homeDetiel.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:homeDetiel animated:YES];
        }else {
            NSLog(@"随手拍");
            
            [self getActDetailsRequestForid:[NSString stringWithFormat:@"%ld",[dic[@"news_id"] integerValue]]];
            
        }
    }else {
        
        NSLog(@"新闻");
        NewsDetailsViewController * homeDetiel = [[NewsDetailsViewController alloc]init];
        homeDetiel.news_idStr = [NSString stringWithFormat:@"%ld",[dic[@"news_id"] integerValue]];
        //        homeDetiel.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:homeDetiel animated:YES];
        
    }

  
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    NSDictionary * dic = _dataArray[indexPath.row];
        
        NSArray * imageArray = dic[@"cover_pic"];
        
        if (imageArray.count!=1) {
            
            static NSString * cellid = @"cellNews";
            
            UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:cellid];
            if (cell==nil) {
                cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:cellid];
            }else {
                
                while ([cell.contentView.subviews lastObject] !=nil) {
                    
                    [(UIView *)[cell.contentView.subviews lastObject] removeFromSuperview];
                }
            }
            
            UILabel * titleLabel  = [[UILabel alloc]initWithFrame:CGRectMake(10, 15, WIDTH -20, 20)];
            titleLabel.text = dic[@"title"];
            titleLabel.font = [UIFont systemFontOfSize:16];
            titleLabel.numberOfLines = 2;
            [titleLabel sizeToFit];
            
            [cell.contentView addSubview:titleLabel];
            CGFloat widthImage = (WIDTH -40)/3;
            UIImageView * image;
            
            
            
            if (imageArray.count==0) {
                
                image = [[UIImageView alloc]initWithFrame:CGRectMake(10,CGRectGetMaxY(titleLabel.frame)+10 ,10 ,1)];
            }else {
                
                for (int i = 0; i<imageArray.count; i++) {
                    
                    image = [[UIImageView alloc]initWithFrame:CGRectMake(10+widthImage*i+10*i, CGRectGetMaxY(titleLabel.frame)+10, widthImage, widthImage *0.6)];
                    [image sd_setImageWithURL:ImageUrl(imageArray[i])];
                    image.layer.cornerRadius = 3.f;
                    image.layer.masksToBounds = YES;
                    [cell.contentView addSubview:image];
                }
                
            }
            
            UIImageView * messageView  =[[UIImageView alloc]initWithFrame:CGRectMake(10, CGRectGetMaxY(image.frame)+10, 18, 18)];
            messageView.image = ImageName(@"home_comment_default");
            [cell.contentView addSubview:messageView];
            
            UILabel * comment = [[UILabel alloc]initWithFrame:CGRectMake(30, CGRectGetMaxY(image.frame)+10, 50, 18)];
            comment.font = [UIFont systemFontOfSize:13];
            comment.text= [NSString stringWithFormat:@"%ld",[dic[@"comment_num"] integerValue]];
            comment.textColor  = [UIColor lightGrayColor];
            comment .numberOfLines = 1;
            [comment sizeToFit];
            
            [cell.contentView addSubview:comment];
            
            UIImageView * lookView  =[[UIImageView alloc]initWithFrame:CGRectMake(CGRectGetMaxX(comment.frame)+10, CGRectGetMaxY(image.frame)+10, 18, 18)];
            lookView.image = ImageName(@"home_watch_default");
            [cell.contentView addSubview:lookView];
            
            UILabel * look = [[UILabel alloc]initWithFrame:CGRectMake(CGRectGetMaxX(lookView.frame)+3, CGRectGetMaxY(image.frame)+10, 50, 18)];
            look.font = [UIFont systemFontOfSize:13];
            look.text= [NSString stringWithFormat:@"%ld",[dic[@"view_num"] integerValue]];
            look.textColor  = [UIColor lightGrayColor];
            look .numberOfLines = 1;
            [look sizeToFit];
            [cell.contentView addSubview:look];
            
            UILabel * time = [[UILabel alloc]initWithFrame:CGRectMake(WIDTH -150, CGRectGetMaxY(image.frame)+10, 140, 18)];
            time.font = [UIFont systemFontOfSize:13];
            time.text= [NSString stringWithFormat:@"%@",dic[@"create_time"]];
            time.textColor  = [UIColor lightGrayColor];
            time.textAlignment = NSTextAlignmentRight;
            
            [cell.contentView addSubview:time];
            
         
            return cell;
            
            
        }else {  // 单图
            SHNesHomeTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"SHNesHomeTableViewCell" forIndexPath:indexPath];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            
            [cell.image sd_setImageWithURL:ImageUrl(dic[@"cover_pic"][0])];
            
            if (ISP5||ISP4) {
                cell.image.frame = CGRectMake(10, (100 -((WIDTH -40)/3 * 0.7))/2, (WIDTH -40)/3, (WIDTH -40)/3 * 0.7);
            }else {
                cell.image.frame = CGRectMake(10, (100 -((WIDTH -40)/3 * 0.6))/2, (WIDTH -40)/3, (WIDTH -40)/3 * 0.6);
            }
            cell.image.layer.cornerRadius = 3.f;
            cell.image.layer.masksToBounds = YES;
            cell.commentNumber.text = [NSString stringWithFormat:@"%ld",[dic[@"comment_num"] integerValue]];
            
            if (ISP5||ISP4) {
                cell.titleLabel.frame = CGRectMake((WIDTH -40)/3 +20, 15, WIDTH -((WIDTH -40)/3-5)-20, 20);
            }else{
                cell.titleLabel.frame = CGRectMake((WIDTH -40)/3 +20, 12, WIDTH -((WIDTH -40)/3-5)-20, 20);
            }
            cell.titleLabel.text  = dic[@"title"];
            cell.titleLabel.numberOfLines = 2;
            [cell.titleLabel sizeToFit];
            
            cell.commentNumber.numberOfLines = 1;
            [cell.commentNumber sizeToFit];
            
            cell.commentImage.frame = CGRectMake((WIDTH -40)/3+20, 70, 18, 18);
            cell.commentNumber.frame  = CGRectMake((WIDTH -40)/3 + 40, 70, 18, 18);
            cell.lookImage.frame = CGRectMake(CGRectGetMaxX(cell.commentNumber.frame)+10, 70, 18, 18);
            
            
            cell.timeLabel.frame = CGRectMake(CGRectGetMaxX(cell.lookImage.frame)+3, 70, WIDTH - (CGRectGetMaxX(cell.lookImage.frame)+10), 18);
            
            if (ISP5||ISP4) {
                cell.time.hidden =YES;
                
                cell.timeLabel.text = [NSString stringWithFormat:@"%ld  %@",[dic[@"view_num"] integerValue],dic[@"create_time"]];
            }else {
                
                cell.timeLabel.text = [NSString stringWithFormat:@"%ld",[dic[@"view_num"] integerValue]];
                cell.time.frame =  CGRectMake(WIDTH -150, CGRectGetMaxY(cell.timeLabel.frame)-18, 140, 18);
                
                cell.time.text= [NSString stringWithFormat:@"%@",dic[@"create_time"]];
                
                cell.time.textAlignment = NSTextAlignmentRight;
                
            }
            
            [cell setViewBottomShadow];
            return cell;
     
     }
        
}

-(UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{

    return nil;
    
}

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    //左滑删除
    return UITableViewCellEditingStyleDelete;
    
}
//修改左滑删除按钮的title
- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return @"删除";
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete)
    {
        page = 1;
        NSDictionary * dic = _dataArray[indexPath.row];
        
        NSString * str = [NSString stringWithFormat:@"%ld",[dic[@"id"]  integerValue]];

        if (_isShare) {
            
            [self deledateShareRequestForNewsId:str];
        }else {
            
            [self deledateCollectRequestForNewsId:str];
        }
       
        
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view.
    }
    
}


-(void)getActDetailsRequestForid:(NSString *)newsId{
    
    NSDictionary * dic = @{@"news_id":newsId,
                           @"user_id":USER_DEFAULTGet(@"user_id")
                           };
    
    
    [PostNetWorking postNetWorkingStr:RequestUrlStr(activity_details_api) andparameters:dic Success:^(id responseObject) {
        
        NSDictionary *  dataDic = responseObject;
        NSLog(@"responseObject = %@",responseObject);
        
        
        
        NSLog(@"responseObject = %@",responseObject);
        
        USER_DEFAULTSet(dataDic[@"pic_url"], @"actDetailsIamgeArray");
        USER_DEFAULTSet(dataDic[@"is_fabulous"], @"act_is_fabulous");
        
        
        if ([dataDic[@"pic_url"] isKindOfClass:[NSArray class]]) {
            NSArray * array = dataDic[@"pic_url"];
            if (array.count==0) {
                
                USER_DEFAULTSet(@"http://a1.qpic.cn/psb?/V147v55d35m6eX/xXdZ2De4s1iE5gYJaikuWyqltDsmFf*LHHZ1ANFPtso!/m/dDABAAAAAAAA&bo=eAB4AAAAAAADByI!&rf=photolist", @"shareImage");
            }else {
                
                USER_DEFAULTSet(dataDic[@"pic_url"][0], @"shareImage");
            }
        }
        NSString * newsId= [NSString stringWithFormat:@"%ld",[dataDic[@"id"] integerValue]];
        USER_DEFAULTSet(newsId,@"shareNewsId");
        USER_DEFAULTSet(@"2",@"shareType");
        USER_DEFAULTSet(dataDic[@"title"], @"shareTitle");
        USER_DEFAULTSet(dataDic[@"content"], @"shareContent");
        USER_DEFAULTSet(dataDic[@"share_url"], @"shareUrl");
        
        
        ActiveDetailViewController * activeDetail = [[ActiveDetailViewController alloc]init];
        activeDetail.actIdStr = newsId;
        activeDetail.dataDic = dataDic;
        activeDetail.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:activeDetail animated:YES];
        
        
    } failed:^(NSURLSessionDataTask * _Nullable task,NSError *error) {
        
        NSHTTPURLResponse * responses = (NSHTTPURLResponse *)task.response;
        if (responses.statusCode == 404) {
            SHuiMBhudTextTimeStr(@"未获取到数据");
        }else {
            SHuiMBhudTextNetError;
        }
    }];
    
}

-(void)getCollectRequest{
    
    NSDictionary * dic = @{@"page":[NSString stringWithFormat:@"%d",page],
                           @"user_id":USER_DEFAULTGet(@"user_id"),
                           @"token":USER_DEFAULTGet(@"token"),
                           @"mac_code":[SHJudgeTools getDeviceId]
                           };
  
    [PostNetWorking postNetWorkingStr:RequestUrlStr(get_collectList_api) andparameters:dic Success:^(id responseObject) {
        
        if ([responseObject isKindOfClass:[NSArray class]]) {
            NSArray * array = responseObject;
            
            if (page == 1) {
                if (_dataArray) {
                    [_dataArray removeAllObjects];
                }
                for (NSDictionary * dic in array) {
                    
                    [_dataArray addObject:dic];
                }
            }else {
                for (NSDictionary * dic in array) {
                    
                    [_dataArray addObject:dic];
                }
            }
            
            [_tableView reloadData];
        }else{
            
            SHuiMBhudTextTimeStr(responseObject[@"msg"]);
        }
        
        [_tableView.mj_header endRefreshing];
        [_tableView.mj_footer endRefreshing];
        NSLog(@"responseObject = %@",responseObject);
        
    } failed:^(NSURLSessionDataTask * _Nullable task,NSError *error) {
        [_tableView.mj_header endRefreshing];
        [_tableView.mj_footer endRefreshing];
        NSHTTPURLResponse * responses = (NSHTTPURLResponse *)task.response;
        if (responses.statusCode == 404) {
            SHuiMBhudTextTimeStr(@"未获取到数据");
        }else {
            SHuiMBhudTextNetError;
        }
    }];
}

-(void)getShareRequest{
    
    NSDictionary * dic = @{
                           @"user_id":USER_DEFAULTGet(@"user_id"),
                           @"token":USER_DEFAULTGet(@"token"),
                           @"mac_code":[SHJudgeTools getDeviceId]
                           };
    
    [PostNetWorking postNetWorkingStr:RequestUrlStr(get_myShareList_api) andparameters:dic Success:^(id responseObject) {
        
        if ([responseObject isKindOfClass:[NSArray class]]) {
            NSArray * array = responseObject;
            
            if (page == 1) {
                if (_dataArray) {
                    [_dataArray removeAllObjects];
                }
                for (NSDictionary * dic in array) {
                    
                    [_dataArray addObject:dic];
                }
            }else {
                for (NSDictionary * dic in array) {
                    
                    [_dataArray addObject:dic];
                }
            }
            
            [_tableView reloadData];
        }else{
            
            SHuiMBhudTextTimeStr(responseObject[@"msg"]);
        }
        
        [_tableView.mj_header endRefreshing];
        [_tableView.mj_footer endRefreshing];
        NSLog(@"responseObject = %@",responseObject);
        
    } failed:^(NSURLSessionDataTask * _Nullable task,NSError *error) {
        [_tableView.mj_header endRefreshing];
        [_tableView.mj_footer endRefreshing];
        NSHTTPURLResponse * responses = (NSHTTPURLResponse *)task.response;
        if (responses.statusCode == 404) {
            SHuiMBhudTextTimeStr(@"未获取到数据");
        }else {
            SHuiMBhudTextNetError;
        }
    }];
}

-(void)deledateCollectRequestForNewsId:(NSString *)ids{

    NSString * idsStr= [NSString stringWithFormat:@"{\"ids\":[%@]}",ids];
    
    NSLog(@"idsStr = %@",idsStr);
    NSDictionary * dic = @{
                           @"user_id":USER_DEFAULTGet(@"user_id"),
                           @"token":USER_DEFAULTGet(@"token"),
                           @"mac_code":[SHJudgeTools getDeviceId],
                           @"batch":idsStr
                           };
    
    NSLog(@"dic = %@",dic);
    
    [PostNetWorking postNetWorkingStr:RequestUrlStr(deledate_collect_api) andparameters:dic Success:^(id responseObject) {
       
        [self getCollectRequest];
       
    } failed:^(NSURLSessionDataTask * _Nullable task,NSError *error) {
      
        NSHTTPURLResponse * responses = (NSHTTPURLResponse *)task.response;
        
        if (responses.statusCode == 404) {
            SHuiMBhudTextTimeStr(@"未获取到数据");
        }else {
            SHuiMBhudTextNetError;
        }
    }];
}

-(void)deledateShareRequestForNewsId:(NSString  *)news{
    
       NSString * idsStr= [NSString stringWithFormat:@"{\"ids\":[%@]}",news];
    NSDictionary * dic = @{
                           @"user_id":USER_DEFAULTGet(@"user_id"),
                           @"token":USER_DEFAULTGet(@"token"),
                           @"mac_code":[SHJudgeTools getDeviceId],
                           @"batch":idsStr
                           };

    [PostNetWorking postNetWorkingStr:RequestUrlStr(deledate_share_api) andparameters:dic Success:^(id responseObject) {

        [self getCollectRequest];

    } failed:^(NSURLSessionDataTask * _Nullable task,NSError *error) {

        NSHTTPURLResponse * responses = (NSHTTPURLResponse *)task.response;
        if (responses.statusCode == 404) {
            SHuiMBhudTextTimeStr(@"未获取到数据");
        }else {
            SHuiMBhudTextNetError;
        }
    }];
}


@end
